<?php
//商品分类模型
class CategoryModel extends Model {
	//获取所有的分类
	public function getCats(){
		$sql = "SELECT * FROM {$this->table}";
		// return $this->db->getAll($sql);
		$cats = $this->db->getAll($sql);
		return $this->tree($cats);
	}

	//定义一个tree，实现重新排序
	public function tree($arr,$pid = 0,$level = 0) {
		static $tree = array();
		foreach ($arr as $v) {
			if ($v['parent_id'] == $pid) {
				//说明找到，先保存level值
				$v['level'] = $level;
				$tree[] = $v;
				//继续查找，以当前分类为准，就是递归
				$this->tree($arr,$v['cat_id'],$level+1);
			}
		}
		return $tree;
	}

	//指定一个分类，找其所有后代分类的id
	public function getSubIds($cat_id){
		$sql = "SELECT * FROM {$this->table}";
		$cats = $this->db->getAll($sql);
		$cats = $this->tree($cats,$cat_id); //传递一个cat_id参数
		$ids = array();
		foreach ($cats as $v) {
			$ids[] = $v['cat_id'];
		}
		//把当前cat_id也追加到数组中
		$ids[] = $cat_id;
		return $ids;
	}
}